#-*- coding:utf-8 -*-
from docx import Document
from docx.document import Document as Doc
import re
import json


def load_setting():
    '''
    获取设置
    :return:
    '''
    with open('config.json', 'r', encoding='utf-8') as f:
        setting = json.load(f)
    return setting

def re_filter(filter_str):
    return  re.compile(r'{}'.format(filter_str))

def read_word_new(path):
    doc = Document(path)

    word_list = []
    filter_dict = {}
    for key, value in load_setting().items():
        if value != '':
            filter_dict[key] = re_filter(value)

    for no, p in enumerate(doc.paragraphs):
        content_dict = {}
        if p.style.name.startswith(f'Heading'):
            content_dict['style'] = p.style.name
            content_dict['content'] = p.text
            word_list.append(content_dict)
        else:
            for k, v in filter_dict.items():
                if v.search(p.text):
                    content_dict['style'] = k
                    content_dict['content'] = p.text
            word_list.append(content_dict)
    # print (word_list)
    return word_list


def caculate_title_and_logical(doc_path):
    '''
    生成表头
    :param path:
    :return:
    '''
    result_list = read_word_new(doc_path)
    # print(result_list)

    title_leavel = []
    for i in result_list:
        if not i:
            continue
        title_leavel.append(i['style'])
    # print(title_leavel)


    max_heading = []
    number_filter = re.compile(r'[0-9]+')
    for heading in title_leavel:
        if number_filter.search(heading):
            max_heading.append(int(number_filter.search(heading).group()))

    logicalfile_heading = []
    for i in result_list:
        if not i:
            continue
        if i['style'].find('DESCRIB') != -1:
            logicalfile_heading.append(i['style'])

    return max(max_heading),set(logicalfile_heading)

def read_word_logical_file_position(path):
    '''
        返回一个列表，包含word文件每行类型，内容
        :param path: 文件路径
        :return: 列表
        '''
    word_list = read_word_new(path)
    max_leavel,_ = caculate_title_and_logical(path)
    print('标题等级最大为', max_leavel)

        # if no == 1000:
        #     break
    if max_leavel == 3:
        title_list = []
        head1 = ''
        head2 = ''
        head3 = ''

        for i in word_list:
            if not i:
                continue
            style = i['style']
            content = i['content']
            if style == 'Heading 1':
                head1 = content
            if style == 'Heading 2':
                head2 = content
            if style == 'Heading 3':
                head3 = content
            if style == 'DATA_FILE':
                if head3 == '':
                    title_list.append((head1, head2, ''))
                else:
                    title_list.append((head1, head2, head3))
        for i in title_list:
            print(i)
        return title_list

    if max_leavel == 4:
        title_dict = {}
        count = 0

        head1 = ''
        head2 = ''
        head3 = ''
        head4 = ''

        for i in word_list:
            if not i:
                continue
            style = i['style']
            content = i['content']
            if style == 'Heading 1':
                head1 = content
            if style == 'Heading 2':
                head2 = content
            if style == 'Heading 3':
                head3 = content
            if style == 'Heading 4':
                head4 = content
            if style == 'DATA_FILE':
                count += 1
                if head3 == '':
                    title_dict['title_list'+str(count)] = []
                    title_dict['title_list'+str(count)].append((head1, head2, '', ''))
                if head4 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, ''))
                else:
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, head4))

            for key, value in load_setting().items():
                if key == 'DATA_FILE':
                    pass
                else:
                    if style == key:
                        title_dict['logical_list' + str(count)] = []
                        title_dict['logical_list' + str(count)].append(content)

        return title_dict
    
    if max_leavel == 5:
        title_dict = {}
        count = 0

        head1 = ''
        head2 = ''
        head3 = ''
        head4 = ''
        head5 = ''

        for i in word_list:
            if not i:
                continue
            style = i['style']
            content = i['content']
            if style == 'Heading 1':
                head1 = content
            if style == 'Heading 2':
                head2 = content
            if style == 'Heading 3':
                head3 = content
            if style == 'Heading 4':
                head4 = content
            if style == 'DATA_FILE':
                count += 1
                if head3 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, '', '',''))
                if head4 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, '',''))
                if head5 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, head4,''))
                else:
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, head4,head5))

            for key, value in load_setting().items():
                if key == 'DATA_FILE':
                    pass
                else:
                    if style == key:
                        title_dict['logical_list' + str(count)] = []
                        title_dict['logical_list' + str(count)].append(content)

        # for i in title_list:
        #     print(i)
        return title_dict

    if max_leavel == 6:
        title_dict = {}
        count = 0

        head1 = ''
        head2 = ''
        head3 = ''
        head4 = ''
        head5 = ''
        head6 = ''

        for i in word_list:
            if not i:
                continue
            style = i['style']
            content = i['content']
            if style == 'Heading 1':
                head1 = content
            if style == 'Heading 2':
                head2 = content
            if style == 'Heading 3':
                head3 = content
            if style == 'Heading 4':
                head4 = content
            if style == 'DATA_FILE':
                count += 1
                if head3 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, '', '', '',''))
                if head4 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, '', '',''))
                if head5 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, head4, '',''))
                if head6 == '':
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, head4,head5,''))
                else:
                    title_dict['title_list' + str(count)] = []
                    title_dict['title_list' + str(count)].append((head1, head2, head3, head4, head5,head6))

            for key, value in load_setting().items():
                if key == 'DATA_FILE':
                    pass
                else:
                    if style == key:
                        title_dict['logical_list' + str(count)] = []
                        title_dict['logical_list' + str(count)].append(content)

        # for i in title_list:
        #     print(i)
        return title_dict

def logical_file_position(path):
    doc = Document(path)

    word_list = []
    INTENEL_FILE_DESCRIB = re.compile(r'本事务功能涉及到的DATA_FILE')

    for no, p in enumerate(doc.paragraphs):
        content_dict = {}
        if p.style.name.startswith(f'Heading'):
            content_dict['style'] = p.style.name
            content_dict['content'] = p.text
            word_list.append(content_dict)
        else:
            if INTENEL_FILE_DESCRIB:
                if INTENEL_FILE_DESCRIB.search(p.text):
                    content_dict['style'] = 'DATA_FILE'
                    content_dict['content'] = p.text
            word_list.append(content_dict)


    for i in word_list:
            if not i:
                continue
            title_leavel.append(i['style'])
            style = i['style']


def create_title(doc_path):
    '''
    生成表头
    :param doc_path: 文件路径
    :return: 列表
    '''
    max_title,logicalfile_heading = caculate_title_and_logical(doc_path)
    title = []
    for i in range(max_title):
        title.append(f'{i + 1}级标题')

    setting_dict = load_setting()

    for i in logicalfile_heading:
        title.append(setting_dict[i])

    print(title)




if __name__ == '__main__':
    from pathlib import Path

    p = Path(r'./')
    doc_path = p / '样本2.docx'
    create_title(doc_path)

    result_list = read_word_logical_file_position(doc_path)
    print(result_list)